import collections
from typing import List


class Solution:
    def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
        m, n = len(matrix), len(matrix[0])

        # 计算前缀和
        prefix = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                prefix[i][j] = matrix[i - 1][j - 1] + prefix[i - 1][j] + prefix[i][j - 1] - prefix[i - 1][j - 1]

        # for row in prefix:
        #     print(row)

        ans = 0
        for i1 in range(m):
            for i2 in range(i1, m):
                memo = collections.Counter({0: 1})
                for j in range(n):
                    val = prefix[i2 + 1][j + 1] - prefix[i1][j + 1]
                    ans += memo[val - target]
                    memo[val] += 1
                    # print(i1, i2, j, "->", val, "->", ans)

        return ans


if __name__ == "__main__":
    # 4
    print(Solution().numSubmatrixSumTarget(matrix=[[0, 1, 0],
                                                   [1, 1, 1],
                                                   [0, 1, 0]],
                                           target=0))

    # 5
    print(Solution().numSubmatrixSumTarget(matrix=[[1, -1],
                                                   [-1, 1]],
                                           target=0))
